package com.redlight.base;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;
import com.redlight.utils.StringUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * Created by chao on 2019/1/9.
 */
public class WebUtil extends WebUtils {
    private static final String urlSuffix = Global.getUrlSuffix();
    private static final String[] staticFiles = StringUtils.split(Global.getConfig("web.staticFile"), ",");

    public WebUtil() {
    }

    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception var1) {
            return null;
        }
    }

    public static String getRootPath(HttpServletRequest request) {
        String rootPath = "";
        if(null == request) {
            request = getRequest();
        }

        if(null != request) {
            rootPath = "http://" + request.getServerName();
            int serverPort = request.getServerPort();
            if(0 < serverPort) {
                rootPath = rootPath + ":" + serverPort;
            }

            rootPath = rootPath + request.getContextPath();
        }

        return rootPath;
    }

    public static InputStream getWebResByUrl(HttpServletRequest request, String resourceName) throws IOException {
        InputStream inputStream = null;
        HttpURLConnection conn = null;

        try {
            String urlStr = resourceName;
            if(!resourceName.toLowerCase().startsWith("http:") && !resourceName.toLowerCase().startsWith("https:") && !resourceName.toLowerCase().startsWith("ftp:")) {
                urlStr = "http://localhost:" + request.getServerPort() + request.getContextPath() + resourceName;
            }

            System.out.println(">>>>>>>>>下载文件地址：" + urlStr);
            URL url = new URL(urlStr);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(6000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
        } catch (MalformedURLException var10) {
            var10.printStackTrace();
        } catch (IOException var11) {
            var11.printStackTrace();
            throw var11;
        } finally {
            if(null != conn) {
                ;
            }

        }

        return inputStream;
    }

    public static void fileDownload(HttpServletResponse response, InputStream ins, String fileName, boolean openFlag) {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", (openFlag?"inline":"attachment") + ";filename=" + StringUtil.strToISO(fileName));
        if(null != ins) {
            try {
                IOUtils.copy(ins, response.getOutputStream());
            } catch (IOException var8) {
                var8.printStackTrace();
            } finally {
                IOUtils.closeQuietly(ins);
            }
        }

    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if(StringUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if(StringUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if(StringUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }

        return remoteAddr != null?remoteAddr:request.getRemoteAddr();
    }

    public static boolean isStaticFile(String uri) {
        if(staticFiles == null) {
            try {
                throw new Exception("检测到“app.properties”中没有配置“web.staticFile”属性。配置示例：\n#静态文件后缀\nweb.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.crx,.xpi,.exe,.ipa,.apk");
            } catch (Exception var2) {
                var2.printStackTrace();
            }
        }

        return StringUtil.endsWithAny(uri, staticFiles) && !StringUtil.endsWithAny(uri, new CharSequence[]{urlSuffix}) && !StringUtil.endsWithAny(uri, new CharSequence[]{".jsp"}) && !StringUtil.endsWithAny(uri, new CharSequence[]{".java"}) && !uri.startsWith("/servlet/");
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String queryString = request.getQueryString();

        try {
            queryString = queryString + "&" + request.getQueryString();
        } catch (Exception var4) {
            ;
        }

        String accept = request.getHeader("accept");
        String xRequestedWith = request.getHeader("X-Requested-With");
        return accept != null && accept.contains("application/json") || xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest") || null != queryString && queryString.contains("__ajax") || null != request.getParameter("isMobile");
    }

    public static Page getParameterPage(Map formMap) {
        Page retPage = new Page();
        if(null == formMap) {
            return retPage;
        } else {
            int pageNo = MapUtil.getIntValue(formMap, "page.pageNo");
            if(0 < pageNo) {
                retPage.setPageNo(pageNo);
            }

            int pageSize = MapUtil.getIntValue(formMap, "page.pageSize");
            if(0 < pageSize) {
                retPage.setPageSize(pageSize);
            }

            String orderBy = MapUtil.getString(formMap, "page.orderBy");
            if(StringUtil.isNotBlank(orderBy)) {
                retPage.setOrderBy(orderBy);
            }

            return retPage;
        }
    }

    public static ServletContext getServletContext() {
        try {
            WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
            ServletContext servletContext = webApplicationContext.getServletContext();
            return servletContext;
        } catch (Exception var2) {
            return null;
        }
    }
}
